package com.app.shop.demo.adapters;

import android.content.Context;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.app.shop.demo.MyApplication;
import com.app.shop.demo.R;
import com.app.shop.demo.beans.GoodsBean;
import com.app.shop.mylibrary.base.CommonAdapter;
import com.app.shop.mylibrary.base.ViewHolder;
import com.app.shop.mylibrary.beans.EventMessage;
import com.app.shop.mylibrary.utils.SharedPreferencesUtil;
import com.app.shop.mylibrary.utils.ToastUtil;
import com.app.shop.mylibrary.utils.UserManager;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;

/**
 * @anthor : w
 * @description :
 */


public class   HomeListAdapter extends CommonAdapter {
    public HomeListAdapter(Context context, ArrayList datas, int layoutId) {
        super(context, datas, layoutId);
    }

    @Override
    public void setView(ViewHolder holder, Object o, int position) {
        GoodsBean bean = (GoodsBean) o;
        SimpleDraweeView simpleDraweeView = holder.getView(R.id.imgv_list);
        TextView tv = holder.getView(R.id.tv_list_item);
        TextView tv_price = holder.getView(R.id.tv_price);
        TextView tv_add = holder.getView(R.id.tv_add);

        tv.setText(bean.getGoods_name());
        tv_price.setText(bean.getGoods_price() + "");
        simpleDraweeView.setImageResource(bean.getGoods_pic());

        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果购物车有该商品，则增加一条，如果没有则添加商品
                if (UserManager.isLogin(getAdapterContext())) {
                    if (MyApplication.goodsBeanList.contains(bean)) {
                        for (int i = 0; i < MyApplication.goodsBeanList.size(); i++) {
                            if (MyApplication.goodsBeanList.get(i).getGoods_id() == bean.getGoods_id()) {
                                MyApplication.goodsBeanList.get(i).setGoods_num(MyApplication.goodsBeanList.get(i).getGoods_num() + 1);
                            }
                        }
                    } else {
                        MyApplication.goodsBeanList.add(bean);
                    }
                    ToastUtil.showToast(getAdapterContext(), "添加成功");
                    EventBus.getDefault().post(new EventMessage(EventMessage.REFRESH));
                } else {
                    ToastUtil.showToast(getAdapterContext(), "请先登录");
                }
            }
        });
    }
}
